package com.ldzy.exception;

import com.ldzy.pojo.MyResponse;
import com.ldzy.pojo.ResultCode;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@ControllerAdvice
public class MyExceptionHandler {
    //这里是统一集中处理异常的方法，每一个方法对应处理一种异常

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public MyResponse exceptionParamHandler(MethodArgumentNotValidException e){
        //发生某种异常时，到这里执行
        System.out.println("exceptionParamHandler");
        MyResponse<Object> myResponse = new MyResponse<>(ResultCode.ERROR_PARAM);
        List<ObjectError> allErrors = e.getAllErrors();
        String msg="";
        for(ObjectError error:allErrors){
            msg=msg+"|"+error.getDefaultMessage();
        }
        myResponse.setData(msg);
        return myResponse;
    }

    @ExceptionHandler({ArithmeticException.class,NullPointerException.class})
    @ResponseBody
    public MyResponse myExceptionHandler(Exception e){
        //发生某种异常时，到这里执行
        System.out.println("ArithmeticException");
        MyResponse<Object> myResponse = new MyResponse<>(ResultCode.ERROR_PARAM);
        myResponse.setData(e.getMessage());
        return myResponse;
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public MyResponse myExceptionHandler3(){
        //发生某3种异常时，到这里执行
        return new MyResponse(ResultCode.ERROR);
    }
}
